package com.weibo;

import java.util.HashMap;
import java.util.List;

import weibo4android.Count;
import weibo4android.Status;
import weibo4android.WeiboException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.weibo.aawbinterface.InitViews;
import com.weibo.aaweiboasync.AsyncDataLoader;
import com.weibo.adapter.WeiboItemAdapter;
import com.weibo.data.DB;
import com.weibo.data.DBHandler;

/**
 * 首页
 * 
 * @author starry
 * 
 */
public class Home extends Activity implements InitViews {
	private Button titleCreateWeibo;// 写微博按钮
	private LinearLayout titlePoint;// 微博切换
	private TextView titleName;// 微博切换名称
	private ImageView titlePoint_nor;// 微博切换上三角
	private ImageView titlePoint_sel;// 微博切换下三角
	private Button titleRefresh;// 微博刷新按钮
	private ProgressBar titleProgress;// 刷新进度条
	private LinearLayout list_footer;// 微博最后一项，获取更多
	private TextView list_footer_more;// 微博最后一项，获取更多，(更多)
	private LinearLayout list_footer_loading;// 微博最后一项，获取更多，(进度)
	private ListView weiboList;// 所有微博View列表
	private List<Status> statusList;// 所有微博列表
	private List<Status> moreWeibo;// 获取更多的微博
	private HashMap<Long, Count> counts;// 每条微博转为HashMap<微博ID,内容>
	private int foot;// 获取更多微博前的微博数，包括“更多”一项
	private String lastId;// 最后一条微博的ID(Long类型)

	private Gallery homegallery;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homegallery);
		getViews();
		setViews();
		setListeners();
		new AsyncDataLoader(asyncLocalCallback).execute();

	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public void finish() {
		super.finish();

	}

	/**
	 * 异步加载服务器上的微博数据的监听器
	 */
	private AsyncDataLoader.Callback asyncRemoteCallback = new AsyncDataLoader.Callback() {

		@Override
		public void onStart() {
			try {
				statusList = Sina.getInstance().getWeibo().getFriendsTimeline();
				counts = getCounts(statusList);
				saveData(statusList, counts);
			} catch (WeiboException e) {
				e.printStackTrace();
				Log(e.toString());
			}
		}

		@Override
		public void onPrepare() {
			titleRefresh.setVisibility(View.GONE);
			titleProgress.setVisibility(View.VISIBLE);
		}

		@Override
		public void onFinish() {
			WeiboItemAdapter adapter = new WeiboItemAdapter(Home.this, statusList, counts);
			weiboList.setAdapter(adapter);
			homegallery.setAdapter(adapter);
			titleProgress.setVisibility(View.GONE);
			titleRefresh.setVisibility(View.VISIBLE);
		}
	};
	/**
	 * 异步加载本地的微博数据的监听器
	 */
	private AsyncDataLoader.Callback asyncLocalCallback = new AsyncDataLoader.Callback() {

		@Override
		public void onPrepare() {
			titleRefresh.setVisibility(View.GONE);
			titleProgress.setVisibility(View.VISIBLE);
		}

		@Override
		public void onStart() {
			statusList = new DBHandler(Home.this).getStatus();
			counts = new DBHandler(Home.this).getCounts();
		}

		@Override
		public void onFinish() {
			WeiboItemAdapter adapter = new WeiboItemAdapter(Home.this, statusList, counts);
			weiboList.setAdapter(adapter);
			homegallery.setAdapter(adapter);
			titleProgress.setVisibility(View.GONE);
			titleRefresh.setVisibility(View.VISIBLE);
		}
	};

	/**
	 * 异步加载更多的微博数据的监听器
	 */
	private AsyncDataLoader.Callback asyncMoreCallback = new AsyncDataLoader.Callback() {

		@Override
		public void onStart() {
			try {
				moreWeibo = Sina.getInstance().getWeibo().getFriendsTimelineMax(lastId);
				counts = appendCounts(moreWeibo, counts);
			} catch (WeiboException e) {
				e.printStackTrace();
				Log(e.toString());
			}
		}

		@Override
		public void onPrepare() {
			list_footer_more.setVisibility(View.GONE);
			list_footer_loading.setVisibility(View.VISIBLE);
			titleRefresh.setVisibility(View.GONE);
			titleProgress.setVisibility(View.VISIBLE);
			lastId = String.valueOf(statusList.get(statusList.size() - 1).getId());
			foot = weiboList.getCount();
		}

		@Override
		public void onFinish() {
			statusList.addAll(moreWeibo);
			WeiboItemAdapter adapter = new WeiboItemAdapter(Home.this, statusList, counts);
			weiboList.setAdapter(adapter);
			homegallery.setAdapter(adapter);
			weiboList.setSelection(foot);
			list_footer_more.setVisibility(View.VISIBLE);
			list_footer_loading.setVisibility(View.GONE);
			titleRefresh.setVisibility(View.VISIBLE);
			titleProgress.setVisibility(View.GONE);
		}
	};

	/**
	 * 保存微博数据
	 * 
	 * @param status
	 * @param counts
	 */
	private void saveData(List<Status> status, HashMap<Long, Count> counts) {
		DBHandler dbHandler = new DBHandler(Home.this);
		dbHandler.clearTable(DB.HOME_TABLE);
		if (status.size() > 20) { // 只保存前20项
			status = status.subList(0, 19);
		}
		for (int i = 0; i < status.size(); i++) {
			dbHandler.save(status.get(i), counts.get(status.get(i).getId()));
		}
	}

	@Override
	public void getViews() {

		titleCreateWeibo = (Button) findViewById(R.id.titlebar_createWeibo);// 写微博按钮

		titlePoint = (LinearLayout) findViewById(R.id.titlebar_point);// 微博切换按钮
		titleName = (TextView) titlePoint.findViewById(R.id.titlebar_name);// 微博切换按钮中的微博名
		titlePoint_nor = (ImageView) titlePoint.findViewById(R.id.titlebar_point_nor);// 微博切换按钮上三角
		titlePoint_sel = (ImageView) titlePoint.findViewById(R.id.titlebar_point_sel);// 微博切换按钮下三角
		titleRefresh = (Button) findViewById(R.id.titlebar_refresh);// 微博刷新按钮
		titleProgress = (ProgressBar) findViewById(R.id.titlebar_progress);// 微博刷新按钮按下后显示的进度

		weiboList = (ListView) findViewById(R.id.home_weiboList);// 微博列表
		homegallery = (Gallery) findViewById(R.id.gallery);

		list_footer = (LinearLayout) getLayoutInflater().inflate(R.layout.list_footer, null);// 微博列表最后一个view（更多）
		list_footer_more = (TextView) list_footer.findViewById(R.id.footer_more);// （更多）按钮
		list_footer_loading = (LinearLayout) list_footer.findViewById(R.id.footer_loading);// 正在获取更多view
	}

	@Override
	public void setViews() {
		titleCreateWeibo.setVisibility(View.VISIBLE);
		titleName.setVisibility(View.VISIBLE);
		titlePoint.setClickable(true);
		titlePoint_nor.setVisibility(View.VISIBLE);
		titleRefresh.setVisibility(View.VISIBLE);
		try {
			titleName.setText(Sina.getInstance().getWeibo().verifyCredentials().getName());
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		weiboList.addFooterView(list_footer);
	}

	@Override
	public void setListeners() {
		titleCreateWeibo.setOnClickListener(clickListener);
		titlePoint.setOnClickListener(clickListener);
		titleRefresh.setOnClickListener(clickListener);
		weiboList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (arg2 == (weiboList.getCount() - 1)) { // 列表最后一项：显示更多微博
					new AsyncDataLoader(asyncMoreCallback).execute();
					return;
				}
				Sina.getInstance().goToDetail(Home.this, statusList.get(arg2));
			}
		});
	}

	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.titlebar_createWeibo:
				createWeibo();
				break;
			case R.id.titlebar_refresh:
				new AsyncDataLoader(asyncRemoteCallback).execute();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 发表新微博
	 */
	private void createWeibo() {
		Sina.getInstance().updateWeibo(this);
	}

	/**
	 * 获取一个HashMap，以微博ID为key，对应微博的Count为值
	 * 
	 * @param sList
	 * @return
	 */
	private HashMap<Long, Count> getCounts(List<Status> sList) {
		HashMap<Long, Count> counts = new HashMap<Long, Count>();
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < sList.size(); i++) {
			buffer.append(sList.get(i).getId() + ",");
		}
		try {
			List<Count> count = Sina.getInstance().getWeibo()
					.getCounts(buffer.substring(0, buffer.length() - 1));
			for (int i = 0; i < count.size(); i++) {
				counts.put(count.get(i).getId(), count.get(i));
			}
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return counts;
	}

	private HashMap<Long, Count> appendCounts(List<Status> sList, HashMap<Long, Count> counts) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < sList.size(); i++) {
			buffer.append(sList.get(i).getId() + ",");
		}
		try {
			List<Count> count = Sina.getInstance().getWeibo()
					.getCounts(buffer.substring(0, buffer.length() - 1));
			for (int i = 0; i < count.size(); i++) {
				counts.put(count.get(i).getId(), count.get(i));
			}
		} catch (WeiboException e) {
			e.printStackTrace();
			Log(e.toString());
		}
		return counts;
	}

	void Log(String msg) {
		Log.i("weibo", "home--" + msg);
	}

}
